import 'package:digital_man/router/router_utils.dart';
import 'package:flutter/material.dart';
import 'package:agora_rtc_engine/rtc_engine.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:speech_to_text/speech_to_text.dart' as stt;
import '../common/styles.dart';
import '../common/utils/util.dart';
import '../common/widget/common_style.dart';

class AudioCallPage extends StatefulWidget {
  @override
  _AudioCallPageState createState() => _AudioCallPageState();
}

class _AudioCallPageState extends State<AudioCallPage> {
  RtcEngine? _engine;
  bool _joined = true;
  final stt.SpeechToText _speech = stt.SpeechToText(); // 安全初始化
  bool _isListening = true;
  String _transcribedText = 'test33';
  var arguments = RouterUtils.getArgument();

  Future<void> initAgora() async {
    _engine = await RtcEngine.create("e8da53ecd1784eac8f4a24a25deb31f7");
    await _engine?.enableAudio();  
    _engine?.setEventHandler(RtcEngineEventHandler(
      joinChannelSuccess: (channel, uid, elapsed) {
        print("joinChannelSuccess事件成功: $channel, uid: $uid");
        setState(() => _joined = true);
        _joinChannel();
      },
      userJoined: (uid, elapsed) {
        print("remote user joined: uid: $uid");
      },
      userOffline: (uid, reason) {
        print("userOffline: uid: $uid , reason: $reason");
      },
    ));
  }
  
  @override
  void initState() {
     initAgora().then((_) {
      _initSpeechToText().then((_) {
        if (_isListening) {
          _startListening();
        }
      });
    });
  }

   Future<void> _initSpeechToText() async {
    bool available = await _speech.initialize(onError: (error) {
      print('转文字不支持: $error');
    }, onStatus: (status) {
      print('转文字支持: $status');
    });
    print('available==============${available}');
    if (available) {
      setState(() { _isListening = true; });
    } else {
      setState(() { _isListening = false; });
    }
  }

  void _startListening() async{ //转文字开始
    print("转文字开始");
    _speech.listen(
      onResult: (result) {
        setState(() {
          print('输入的语音是: ${result.recognizedWords}');
          _transcribedText = result.recognizedWords;
        });
      },
      listenFor: const Duration(seconds: 60), // 限制监听时长，可根据需要调整
    );
  }

  void _stopListening() {
    if (_isListening) {
      _speech.stop();
      setState(() => _isListening = false);
    }
  }

  void _joinChannel() async {
    await Util.requestMicrophonePermission();
    try {
      String token = DateTime.now().millisecondsSinceEpoch.toString(); // 使用时间戳生成唯一 UID
      // await _engine?.joinChannel(token, "doudou", "dd", uid);
      await _engine?.joinChannel("444", arguments["label"], null, arguments["value"]);
      print("语音启动成功");
    } catch (e) {
      print("语音启动失败: $e");
    }
  }

  void _leaveChannel() async {
    _stopListening(); //停止说话后停止转文字
    await _engine?.leaveChannel();
    setState(() => _joined = false);
  }

  @override
  void dispose() {
    _stopListening(); //停止转文字
    _engine?.destroy();  // 释放Agora资源
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('语音页面'),
      ),
      body: Column(
        children: [
          Expanded(child: Container(
            padding: EdgeInsets.symmetric(horizontal: 120.w),
            decoration: const BoxDecoration(
              color: Styles.black3Color
            ),
            child: Text(_transcribedText, style: textStyle()),
          ),),
        ],
      ),
      floatingActionButton: Column(
        mainAxisAlignment: MainAxisAlignment.end,
        crossAxisAlignment: CrossAxisAlignment.end,
         children: [
          FloatingActionButton(
            onPressed: _joined ? _leaveChannel : _joinChannel,
            child: Icon(_joined ? Icons.call_end : Icons.call),
          ),
          SizedBox(height: 16),
           FloatingActionButton(
            onPressed: _isListening ? _stopListening : _startListening,
            child: Icon(_isListening ? Icons.mic_off : Icons.mic),
          ),
        ],
      ),
    );
  }
}